<script setup lang="ts">
import { isExternal, validNumber } from "@/utils/validate";
import { ref, toRefs, computed, onMounted } from "vue";

import { useFile } from "@/hooks/useFile";
const {
  handleChooseImage,
  getImageUrl,
  initVal,
  batchUpload,
  filesData,
  fileList,
  ish5,
} = useFile("uniapp");

const emit = defineEmits(["update:modelValue"]);
interface Props {
  modelValue: string | string[]; // 绑定元素，单选请传字符串
  accept: string; // 图片类型
  size: number | string; // 图片大小
  multiple: boolean; //是否多选
  autoUpload: boolean; // 是否选择后字段上传
}
const props = withDefaults(defineProps<Props>(), {
  accept: "image/*",
  size: 100,
  autoUpload: true,
  multiple: false,
});

const { accept, modelValue, size } = toRefs(props);

if (props.modelValue) {
  initVal(props.modelValue);
}

const currentVal = computed({
  get() {
    if (!modelValue.value) return [];
    if (typeof modelValue.value === "string") {
      return [modelValue.value];
    }
    return modelValue.value.map((v) => {});
  },
  set(val) {
    if (Array.isArray(val) && !props.multiple) {
      emit("update:modelValue", val[0]);
    } else {
      emit("update:modelValue", val);
    }
  },
});
const classStyle = computed(() => {
  const asize = validNumber(size.value) ? size.value + "px" : size.value;
  return {
    width: asize,
    height: asize,
  };
});
const updateValue = () => {
  const arr = filesData.value.reduce((pre, item) => {
    console.log(item);
    pre.push(item.data?.url);
    return pre;
  }, [] as string[]);

  currentVal.value = arr;
};

const handleUpload = () => {
  console.log("自动上传");
  handleChooseImage({
    multiple: props.multiple,
    autoUpload: props.autoUpload,
    accept: props.accept,
  }).then((res) => {
    console.log("自动上传");
    console.log(res);
    if (props.autoUpload) {
      updateValue();
    }
  });
};

/**
 * 如果是选择文件不上传模式，则此方法提供上传功能
 */
const handleStart = () => {
  return new Promise((resolve, reject) => {
    batchUpload()
      .then((res) => {
        const isSuccess = filesData.value.some((v) => v.status == 2);
        if (isSuccess) {
          updateValue();
          resolve(currentVal.value);
        } else {
          reject();
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};
const handleClick = () => {
  if (props.multiple) return;
  handleUpload();
};
defineExpose({
  handleStart,
});
</script>

<template>
  <div class="uploader-body">
    <div
      class="uploader-body-item"
      :style="classStyle"
      v-for="(item, index) in filesData"
      @click="handleClick"
      :key="index"
    >
      <div class="image">
        <img v-if="ish5" class="image" :src="item.viewUrl" />
        <image v-else class="image" :src="item.viewUrl" mode="scaleToFill" />
        <div
          class="progress"
          :style="{
            height: 100 - item.progress + '%',
          }"
        ></div>
      </div>
    </div>
    <div
      v-if="multiple || filesData.length == 0"
      @click="handleUpload('')"
      :style="classStyle"
      class="uploader-infos"
    >
      <span class="upload-icon"></span>
    </div>

    <!-- <div
      class="uploader"
      :style="classStyle"
      :class="{ active: currentVal }"
      @click="handleUpload('')"
    >
      <div class="uploadProgress" v-if="loading">
        {{ text }}
      </div>

      <div v-if="currentVal" :style="classStyle">
        <img :style="classStyle" :src="currentVal" fit="contain" />
        <div class="upload-close" @click.stop="handleClose">
          <i class="icon iconfont icon-guanbi1"></i>
        </div>
      </div>
  
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.uploader-body {
  display: flex;
  flex-wrap: wrap;
  &-item {
    position: relative;
    margin-bottom: 10px;

    margin-right: 10px;
  }
}
.image {
  width: 100%;
  height: 100%;
  position: relative;
  .progress {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    font-size: 32px;
    background-color: rgba($color: #000000, $alpha: 0.7);
  }
}

.uploader-infos {
  text-align: center;
  padding: 2vw;
  $w: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  .upload-icon {
    position: relative;
    width: $w;
    height: $w;

    display: inline-block;
    &:after {
      position: absolute;
      left: 50%;
      width: 2px;
      height: 100%;
      transform: translate(-1px, 0);
      background-color: #333;
      content: "";
      top: 0;
    }
    &:before {
      position: absolute;
      top: 50%;
      left: 0;
      height: 2px;
      transform: translate(0, -1px);
      width: 100%;
      background-color: #333;
      content: "";
    }
  }
  &-txt {
    .title {
      font-weight: 400;
      font-size: 3.6vw;
      margin-top: 2vw;
    }
    p {
    }
    .info {
      margin-top: 2vw;
      color: #888;
      font-size: 3vw;
    }
  }
}

.hidden {
  display: none;
}
.uploader-body {
  flex: 1;
}
.upload-close {
  position: absolute;
  color: red;
  padding: 2vw;
  right: 0;
  top: 0;
  z-index: 99;
}
.uploader {
  border: 1px dashed #999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.5s;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  outline: none;
  position: relative;

  &.active {
    border: none;
    &:hover {
      .uploader-refresh {
        opacity: 1;
        transform: scale(1);
      }
    }
  }
  .uploader-refresh {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    background-color: rgba($color: #000000, $alpha: 0.5);
    display: inline-flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    cursor: pointer;
    opacity: 0;
    transform: scale(0);
    transition: all 0.2s;
  }
}

.uploadProgress {
  position: absolute;
  left: 0%;
  top: 0%;
  right: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  background-color: rgba($color: #000000, $alpha: 0.7);
  color: #fff;
  --circle-text-color: #fff;
  z-index: 20;
  .uni-progress-bar {
    display: none;
  }
}
.upload-close {
}
</style>
